#include <QtTest>

// add necessary includes here
/*
    智能指针：



    以上代码，若在...期间，QLabel被释放，最后一行不会被执行




QSharedPointer、 QScopedPointer、QWeakPointer、QSharedDataPointer
 QScopedArrayPointer
 */
class SmartPointer : public QObject
{
    Q_OBJECT

public:
    SmartPointer();
    ~SmartPointer();

private slots:
    void test_case1();
    void test_qshareptr();
    void test_qshareptr2();
};

SmartPointer::SmartPointer()
{

}

SmartPointer::~SmartPointer()
{

}

void SmartPointer::test_case1()
{
    //QPointer 保护指针
    //行为类似c++的T*指针，但是QPointer的T必须是QObject的子类。 与普通指针的区别是当对象被销毁，指针将会自动赋空。
    //避免出现“悬空指针”。

    QPointer<QObject> obj = new QObject;
    obj->setObjectName("QPointerTest");

    delete obj; //不需要 obj = nullptr

    if (obj)
        qDebug()<< "objName:" << obj->objectName();
    else
        qDebug() << "obj is nullptr";
}

QSharedPointer<QObject> getObject()
{
    QObject *obj = new QObject();
    obj->setObjectName("测试智能指针对象");
    QObject::connect(obj,&QObject::destroyed,[=]{
        qDebug()<<"obj 被释放";
    });

    QSharedPointer<QObject> ptr = QSharedPointer<QObject>(obj);
    return ptr;
}

void SmartPointer::test_qshareptr()
{
    /*QSharedPointer 共享指针
        多个共享指针可以指向同一个对象，当该对象和最后一个引用消失后，将会释放
    */

    QSharedPointer<QObject> obj = getObject();
    if(obj)
        qDebug() << obj->objectName() << obj.data()->objectName();

    //无需obj->deleteLater();  obj 将会自动释放
}

void SmartPointer::test_qshareptr2()
{
    QSharedPointer<QObject> obj = getObject();
//    delete obj.data();
    if(obj)
        qDebug() << obj->objectName() << obj.data()->objectName();

}

QTEST_APPLESS_MAIN(SmartPointer)

#include "tst_smartpointer.moc"
